/**
 * 二维码历史记录管理 - 使用 IndexedDB
 */

export interface QRCodeHistory {
  id?: number
  content: string
  qrcodeImage: string
  timestamp: number
  hasLogo: boolean
}

export class QRCodeHistoryDB {
  private dbName = 'QRCodeHistoryDB'
  private storeName = 'history'
  private version = 1
  private db: IDBDatabase | null = null

  /**
   * 初始化数据库
   */
  async init(): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version)

      request.onerror = () => {
        reject(new Error('Failed to open database'))
      }

      request.onsuccess = () => {
        this.db = request.result
        resolve()
      }

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result
        
        // 创建对象存储
        if (!db.objectStoreNames.contains(this.storeName)) {
          const store = db.createObjectStore(this.storeName, {
            keyPath: 'id',
            autoIncrement: true
          })
          
          // 创建索引
          store.createIndex('timestamp', 'timestamp', { unique: false })
          store.createIndex('content', 'content', { unique: false })
        }
      }
    })
  }

  /**
   * 确保数据库已初始化
   */
  private async ensureDB(): Promise<void> {
    if (!this.db) {
      await this.init()
    }
  }

  /**
   * 添加历史记录
   */
  async addHistory(data: Omit<QRCodeHistory, 'id'>): Promise<number> {
    await this.ensureDB()
    
    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.add(data)

      request.onsuccess = () => {
        resolve(request.result as number)
      }

      request.onerror = () => {
        reject(new Error('Failed to add history'))
      }
    })
  }

  /**
   * 获取历史记录列表
   * @param limit 限制数量，默认10条
   */
  async getHistory(limit: number = 10): Promise<QRCodeHistory[]> {
    await this.ensureDB()
    
    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readonly')
      const store = transaction.objectStore(this.storeName)
      const index = store.index('timestamp')
      const request = index.openCursor(null, 'prev') // 按时间降序
      const results: QRCodeHistory[] = []

      request.onsuccess = () => {
        const cursor = request.result
        if (cursor && results.length < limit) {
          results.push(cursor.value)
          cursor.continue()
        } else {
          resolve(results)
        }
      }

      request.onerror = () => {
        reject(new Error('Failed to get history'))
      }
    })
  }

  /**
   * 更新历史记录
   */
  async updateHistory(id: number, updates: Partial<QRCodeHistory>): Promise<void> {
    await this.ensureDB()
    
    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const getRequest = store.get(id)

      getRequest.onsuccess = () => {
        const data = getRequest.result
        if (data) {
          const updated = { ...data, ...updates }
          const putRequest = store.put(updated)
          
          putRequest.onsuccess = () => {
            resolve()
          }
          
          putRequest.onerror = () => {
            reject(new Error('Failed to update history'))
          }
        } else {
          reject(new Error('History not found'))
        }
      }

      getRequest.onerror = () => {
        reject(new Error('Failed to get history'))
      }
    })
  }

  /**
   * 删除单条历史记录
   */
  async deleteHistory(id: number): Promise<void> {
    await this.ensureDB()
    
    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.delete(id)

      request.onsuccess = () => {
        resolve()
      }

      request.onerror = () => {
        reject(new Error('Failed to delete history'))
      }
    })
  }

  /**
   * 清空所有历史记录
   */
  async clearHistory(): Promise<void> {
    await this.ensureDB()
    
    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.clear()

      request.onsuccess = () => {
        resolve()
      }

      request.onerror = () => {
        reject(new Error('Failed to clear history'))
      }
    })
  }

  /**
   * 按内容搜索历史记录
   */
  async searchHistory(keyword: string): Promise<QRCodeHistory[]> {
    await this.ensureDB()
    
    const allHistory = await this.getHistory(100) // 获取更多记录进行搜索
    return allHistory.filter(item => 
      item.content.toLowerCase().includes(keyword.toLowerCase())
    )
  }

  /**
   * 获取历史记录总数
   */
  async getHistoryCount(): Promise<number> {
    await this.ensureDB()
    
    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readonly')
      const store = transaction.objectStore(this.storeName)
      const request = store.count()

      request.onsuccess = () => {
        resolve(request.result)
      }

      request.onerror = () => {
        reject(new Error('Failed to count history'))
      }
    })
  }
}